#include "login.h"
#include "ui_login.h"
#include <QMessageBox>
#include<QDebug>
void Login::readFile()
{
    QFile file("account.txt");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
    {
        qDebug()<<"文件打开失败"<<__LINE__<<endl;
        return ;
    }
    Account A;
    QTextStream in(&file);
    while(!in.atEnd())
    {
        in>>A;
        acc.insert(A.getAccount(),A);
    }
    file.close();
}

void Login::writeFile()
{
    QFile file("account.txt");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text))
    {
        qDebug()<<"文件写入失败"<<endl;
        return ;
    }
    QTextStream out(&file);

    for(auto e : acc)
    {
        if(e.getAccount() == "") continue;
        out << e <<endl;
    }

    file.close();
}

Login::Login(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Login),
    register_dialog(nullptr),
    mainwidget(nullptr)
{
    ui->setupUi(this);
    readFile();
    ui->lineEdit_password->setEchoMode(QLineEdit::Password);
}

Login::~Login()
{
    writeFile();
    //qDebug()<<__LINE__<<endl;
    delete ui;
}

void Login::on_pushButton_login_clicked()
{
    QString username = ui->lineEdit_login->text();
    QString password = ui->lineEdit_password->text();
    QMessageBox mess;
    if(acc.find(username) != acc.end() && acc[username].getPassword() == password)
    {
        mess.setText("登录成功！");
        mainwidget = new Widget(this->parentWidget());
        mess.exec();
        mainwidget->show();
        this->hide(); // 隐藏登录窗口

    }
    else
    {
        mess.setText("账号或密码错误!");
        mess.exec();
    }

}

void Login::on_pushButton_register_clicked()
{
    for(auto it = acc.begin();it!=acc.end();it++)
    {
        qDebug()<<it.key()<<endl;
    }

    if(register_dialog == nullptr)
    {
        register_dialog = new register_Dialog();
    }

    int ret = register_dialog->exec();
    if(ret == QDialog::Accepted)
    {
        QStringList accountPassword = register_dialog->getAccount();
        QString account = accountPassword[0];
        QString password = accountPassword[1];

        auto it = acc.find(account);
        QMessageBox message;
        if(it == acc.end())
        {
            acc.insert(account, Account(account, password));
            message.setText("注册成功！");
        }
        else
        {
             message.setText("账号重复，请登录！");
        }
        message.exec();
    }
    delete register_dialog;
    register_dialog = nullptr;
}

void Login::on_checkBox_password_clicked(bool checked)
{
    if(checked == true)
    {
        ui->lineEdit_password->setEchoMode(QLineEdit::Normal);
    }
    else
    {
        ui->lineEdit_password->setEchoMode(QLineEdit::Password);
    }
}
